package com.vanzo.talkie2;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tisen on 2018/1/12.
 */

public class SetActivity extends Activity implements View.OnClickListener {


    private ATHelper atHelper;

    private TextView mode_text, gbw_text, power_text, afc_text, rssi_text;
    private EditText tf_edit, rf_edit, tx_edit, rx_edit, sq_edit;
    private Switch mode_switch, gbw_switch, power_switch;
    private Button set, send, setMic, setVol, setVox, setApc, setAfc, getAfc, getRssi;
    private Spinner micSp, volSp, voxSp;
    private EditText apc_edit, afc_edit;
    private ImageView mic;
    private ProgressDialog progressDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTalkieStatus(TALKIE_STATE_PATH, "1");
        setContentView(R.layout.activity_set);
        atHelper = new ATHelper(this, (Application) getApplication());


        mode_text = (TextView) findViewById(R.id.mode_text);
        gbw_text = (TextView) findViewById(R.id.gbw_text);
        power_text = (TextView) findViewById(R.id.power_text);

        gbw_switch = (Switch) findViewById(R.id.set_gbw);
        mode_switch = (Switch) findViewById(R.id.set_mode);
        tf_edit = (EditText) findViewById(R.id.set_tf_edit);
        rf_edit = (EditText) findViewById(R.id.set_rf_edit);
        tx_edit = (EditText) findViewById(R.id.set_tx_edit);
        rx_edit = (EditText) findViewById(R.id.set_rx_edit);
        sq_edit = (EditText) findViewById(R.id.set_sq_edit);
        power_switch = (Switch) findViewById(R.id.set_power);

        micSp = (Spinner) findViewById(R.id.set_mic_sp);
        volSp = (Spinner) findViewById(R.id.set_vol_sp);
        voxSp = (Spinner) findViewById(R.id.set_vox_sp);
        apc_edit = (EditText) findViewById(R.id.set_apc_edit);
        afc_edit = (EditText) findViewById(R.id.set_afc_edit);
        afc_text = (TextView) findViewById(R.id.get_afc_edit);
        rssi_text = (TextView) findViewById(R.id.get_rssi_edit);

        setApc = (Button) findViewById(R.id.set_apc_button);
        setVox = (Button) findViewById(R.id.set_vox_button);
        setMic = (Button) findViewById(R.id.set_mic_button);
        setVol = (Button) findViewById(R.id.set_vol_button);

        setAfc = (Button) findViewById(R.id.set_afc_button);
        getAfc = (Button) findViewById(R.id.get_afc_button);
        getRssi = (Button) findViewById(R.id.get_rssi_button);

        mic = (ImageView) findViewById(R.id.set_mic_image);

        set = (Button) findViewById(R.id.set_set);
        send = (Button) findViewById(R.id.send);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        setTalkieStatus(TALKIE_STATE_PATH, "0");
        super.onDestroy();
    }

    private void init() {
        progressDialog = ProgressDialog.show(this, null, "正在初始化", false, false);
        connect();

        mode_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mode_text.setText("模式:" + (!isChecked ? "模拟" : "数字"));
            }
        });

        gbw_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                gbw_text.setText("GBW:" + (!isChecked ? "窄带" : "宽带"));
            }
        });

        power_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                power_text.setText("功率:" + (!isChecked ? "低" : "高"));
            }
        });

        set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tf_text = tf_edit.getText().toString();
                String rf_text = rf_edit.getText().toString();
                String tx_text = tx_edit.getText().toString();
                String rx_text = rx_edit.getText().toString();
                String sq_text = sq_edit.getText().toString();
                boolean mode_switchChecked = mode_switch.isChecked();
                boolean gbw_switchChecked = gbw_switch.isChecked();
                boolean power_switchChecked = power_switch.isChecked();
                progressDialog = ProgressDialog.show(SetActivity.this, null, "正在设置", false, false);
                atHelper.setGroup(!mode_switchChecked ? 1 : 2, !gbw_switchChecked ? 0 : 1, tf_text, rf_text, tx_text, rx_text, sq_text, !power_switchChecked ? 0 : 1, setCallback);
            }
        });
        send.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    atHelper.setPtt(0, sendUpCallback);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    atHelper.setPtt(1, sendDownCallback);
                }
                return false;
            }
        });
        setMic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atHelper.setMic(micSp.getSelectedItemPosition() + 1, new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("+DMOSETMIC:0")) {
                            handler.sendEmptyMessage(SET_MIC_SUCCESS);
                        } else {
                            handler.sendEmptyMessage(SET_MIC_FAIL);
                        }
                    }
                });
            }
        });
        setVol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atHelper.setVolume(volSp.getSelectedItemPosition() + 1, new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("+DMOSETVOLUME:0")) {
                            handler.sendEmptyMessage(SET_VOL_SUCCESS);
                        } else {
                            handler.sendEmptyMessage(SET_VOL_FAIL);
                        }
                    }
                });
            }
        });
        setVox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atHelper.setVox(voxSp.getSelectedItemPosition(), new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("+DMOSETVOX:0")) {
                            handler.sendEmptyMessage(SET_VOX_SUCCESS);
                        } else {
                            handler.sendEmptyMessage(SET_VOX_FAIL);
                        }
                    }
                });
            }
        });
        setApc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atHelper.setApc(Integer.parseInt(apc_edit.getText().toString()), new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("+DMOSETAPC:0")) {
                            handler.sendEmptyMessage(SET_APC_SUCCESS);
                        } else {
                            handler.sendEmptyMessage(SET_APC_FAIL);
                        }
                    }
                });
            }
        });
        setAfc.setOnClickListener(this);
        getAfc.setOnClickListener(this);
        getRssi.setOnClickListener(this);

    }

    private ATHelper.Callback setCallback = new ATHelper.Callback() {
        @Override
        public void callback(String result) {
            Log.i("zts", "result : " + result);
            if (result.contains("DMOSETGROUP:0")) {
                handler.sendEmptyMessage(SET_GRO_SUCCESS);
            } else {
                handler.sendEmptyMessage(SET_GRO_FAIL);
            }
        }
    };
    private ATHelper.Callback sendUpCallback = new ATHelper.Callback() {
        @Override
        public void callback(String result) {
            Log.i("zts", "result : " + result);
            if (result.contains("+DMOPTT:0")) {
                refreshMic.sendEmptyMessage(1);
            }
        }
    };
    private ATHelper.Callback sendDownCallback = new ATHelper.Callback() {
        @Override
        public void callback(String result) {
            Log.i("zts", "result : " + result);
            if (result.contains("+DMOPTT:0")) {
                refreshMic.sendEmptyMessage(0);
            }
        }
    };

    private Handler refreshMic = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mic.setImageResource(msg.what == 0 ? R.drawable.mic_image_on : R.drawable.mic_image_off);
        }
    };

    private void connect() {
        timeOut.sendEmptyMessageDelayed(TIME_OUT, 30000);
        timer.schedule(task, 3000, 2000);
    }

    private final Timer timer = new Timer();

    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Log.d(TAG, "zts new task");
            atHelper.setCon(new ATHelper.Callback() {
                @Override
                public void callback(String result) {
                    Log.i("zts", "result : " + result);
                    if (result.contains("DMOCONNECT")) {
                        timer.cancel();
                        timeOut.removeMessages(TIME_OUT);
                        handler.sendEmptyMessage(CONNECT_SUCCESS);
                    }
                }
            });
        }
    };

    private Handler timeOut = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            timer.cancel();
            handler.sendEmptyMessage(CONNECT_FAIL);
        }

    };


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CONNECT_SUCCESS:
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    break;
                case CONNECT_FAIL:
                    Toast.makeText(SetActivity.this, "初始化失败,正在重试", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case SET_GRO_SUCCESS:
                    progressDialog.dismiss();
                    Toast.makeText(SetActivity.this, "设置频道参数成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_GRO_FAIL:
                    Toast.makeText(SetActivity.this, "设置频道参数失败", Toast.LENGTH_SHORT).show();
                    break;
                case SET_MIC_SUCCESS:
                    Toast.makeText(SetActivity.this, "设置麦克风增益成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_MIC_FAIL:
                    Toast.makeText(SetActivity.this, "设置麦克风增益失败", Toast.LENGTH_SHORT).show();
                    break;
                case SET_VOL_SUCCESS:
                    Toast.makeText(SetActivity.this, "设置音量成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_VOL_FAIL:
                    Toast.makeText(SetActivity.this, "设置音量失败", Toast.LENGTH_SHORT).show();
                    break;
                case SET_VOX_SUCCESS:
                    Toast.makeText(SetActivity.this, "设置声控成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_VOX_FAIL:
                    Toast.makeText(SetActivity.this, "设置声控失败", Toast.LENGTH_SHORT).show();
                    break;
                case SET_PTT_SUCCESS:
                    break;
                case SET_PTT_FAIL:
                    break;
                case SET_APC_SUCCESS:
                    Toast.makeText(SetActivity.this, "设置发射功率成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_APC_FAIL:
                    Toast.makeText(SetActivity.this, "设置发射功率失败", Toast.LENGTH_SHORT).show();
                    break;
                case SET_AFC_SUCCESS:
                    Toast.makeText(SetActivity.this, "调整AFC参数成功", Toast.LENGTH_SHORT).show();
                    break;
                case SET_AFC_FAIL:
                    Toast.makeText(SetActivity.this, "调整AFC参数失败", Toast.LENGTH_SHORT).show();
                    break;
                case GET_AFC_SUCCESS:
                    Toast.makeText(SetActivity.this, "获取AFC参数成功", Toast.LENGTH_SHORT).show();
                    String afc = (String) msg.obj;
                    afc_text.setText(afc);
                    break;
                case GET_AFC_FAIL:
                    Toast.makeText(SetActivity.this, "获取AFC参数失败", Toast.LENGTH_SHORT).show();
                    break;
                case GET_RSSI_SUCCESS:
                    Toast.makeText(SetActivity.this, "获取RSSI参数成功", Toast.LENGTH_SHORT).show();
                    String rssi = (String) msg.obj;
                    rssi_text.setText(rssi);
                    break;
                case GET_RSSI_FAIL:
                    Toast.makeText(SetActivity.this, "获取RSSI参数失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private static final int TIME_OUT = 10001;
    private static final int CONNECT_SUCCESS = 100;
    private static final int CONNECT_FAIL = 101;
    private static final int SET_GRO_SUCCESS = 102;
    private static final int SET_GRO_FAIL = 103;
    private static final int SET_MIC_SUCCESS = 104;
    private static final int SET_MIC_FAIL = 105;
    private static final int SET_VOL_SUCCESS = 106;
    private static final int SET_VOL_FAIL = 107;
    private static final int SET_PTT_SUCCESS = 108;
    private static final int SET_PTT_FAIL = 109;
    private static final int SET_APC_SUCCESS = 110;
    private static final int SET_APC_FAIL = 111;
    private static final int SET_AFC_SUCCESS = 112;
    private static final int SET_AFC_FAIL = 113;
    private static final int GET_AFC_SUCCESS = 114;
    private static final int GET_AFC_FAIL = 115;
    private static final int GET_RSSI_SUCCESS = 116;
    private static final int GET_RSSI_FAIL = 117;
    private static final int SET_VOX_SUCCESS = 118;
    private static final int SET_VOX_FAIL = 119;

    private static final String TAG = "SetActivity";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_rssi_button:
                atHelper.getRssi(new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("DMORDRSSI")) {
                            String rssi = result.split(":")[1];
                            Message message = new Message();
                            message.what = GET_RSSI_SUCCESS;
                            message.obj = rssi;
                            handler.sendMessage(message);
                        } else {
                            handler.sendEmptyMessage(GET_RSSI_FAIL);
                        }
                    }
                });
                break;
            case R.id.get_afc_button:
                Log.d("zts", "get_afc_button");
                atHelper.getAfc(new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("DMOGETVAFC")) {
                            Log.d("zts", "result = " + result);
                            String afc = result.split(":")[1];
                            Message message = new Message();
                            message.what = GET_AFC_SUCCESS;
                            message.obj = afc;
                            handler.sendMessage(message);
                        } else {
                            handler.sendEmptyMessage(GET_AFC_FAIL);
                        }
                    }
                });
                break;
            case R.id.set_afc_button:
                atHelper.setAfc(Integer.parseInt(afc_edit.getText().toString()), new ATHelper.Callback() {
                    @Override
                    public void callback(String result) {
                        if (result.contains("+DMOSETVAFC:0")) {
                            handler.sendEmptyMessage(SET_AFC_SUCCESS);
                        } else {
                            handler.sendEmptyMessage(SET_AFC_FAIL);
                        }
                    }
                });
                break;
        }
    }

    private static final String TALKIE_STATE_PATH = "sys/devices/platform/talkie@0/talkieenablestatus";

    private void setTalkieStatus(String path, String node) {
        try {
            BufferedWriter bufWriter = null;
            bufWriter = new BufferedWriter(new FileWriter(path));
            bufWriter.write(node);  // 写操作
            bufWriter.close();
            Log.d(TAG, " write successful talkie = " + node + " by IO");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, " can't write " + path + e.getMessage());
        }
    }
}
